﻿(function () {
    function setIframeSize(wrap, n) {
        function aritcleVideo() {
            var ww = $(document).width(),
				aw = ww - n,
				ch = aw / 16 * 9;
            $(wrap).find('iframe').css({
                'width': aw + 'px',
                'height': ch + 'px'
            });
            $(wrap).find('embed').css({
                'width': aw + 'px',
                'height': ch + 'px'
            });
            if ($('#youkuplayer_0').length != 0) {
                $(wrap).find('#youkuplayer_0').css({
                    'width': aw + 'px',
                    'height': ch + 'px'
                });
            } else if ($('#youkuplayer_1').length != 0) {
                $(wrap).find('#youkuplayer_1').css({
                    'width': aw + 'px',
                    'height': ch + 'px'
                });
            }
        }
        if ($(wrap).length != 0) {
            aritcleVideo();
            setTimeout(function () {
                aritcleVideo();
            }, 2000);
        } else {
            return false;
        }
    }
    setIframeSize('.ymw-contxt', 20);
    setIframeSize('.ymw-rel-infos', 28);
    function downVideo() {
        var ww = $(document).width(),
		aw = ww - 28,
		ch = aw / 16 * 9;
        if ($('.ymw-gmvd').find('.yu-btn-yuan').length == 0) {
            $('.ymw-gmvd').remove();
        } else {
            $('.ymw-gmvd').find('.yu-btn-yuan').addClass('ymwQhYuanBtn');
            $("#gamersky_player_box").GamerSkyPlayer();
            $("#gamersky_player_box").css({ 'width': aw + 'px', 'height': ch + 'px' });
        }
    }
    if ($('.ymw-gmvd').length != 0) {
        downVideo();
    }
    (!$('.ymw-contxt').length == 0) ? contentJs() : void 0;
    if ($('.pingce2').length != 0) {
        addPcNum();
    }
    if ($('.dianping').length != 0) {
        addPcNum();
    }
})();

(function ($) {
    $.fn.wanFun = function () {
        var ids = "";
        $(".tpbtn[data-type='7']").each(function () {
            if (ids != "") {
                ids = ids + ","
            }
            ids = ids + $(this).attr("gameid");
        });
        $.ajax({
            type: "GET",
            dataType: "jsonp",
            url: "http://cm1.gamersky.com/apirating/getwanrating",
            data: { 'Idlist': ids },
            success: function (data) {
                if (data.status == 'ok') {
                    $.each(data.result, function (index, value) {
                        $(".tpbtn[gameid='" + value.gameId + "'][data-type='7']").find("i").text(value.wantplayCount);
                        $(".tpbtn[gameid='" + value.gameId + "'][data-type='8']").find("i").text(value.playedCount);
                    });
                }
            }
        });
    };
    $.fn.addwanFun = function () {
        return this.each(function () {
            var $this = $(this);
            if ($this.attr("data-click") == "false") {
                $this.attr("data-click", true);
                var Id = $this.attr("gameid");
                var type = $this.attr("data-type");
                $.ajax({
                    type: "GET",
                    dataType: "jsonp",
                    url: "http://cm1.gamersky.com/apirating/addwanRating",
                    data: { 'Rating': JSON2.stringify({ "GenneralId": Id, 'Sorce': "1", 'Type': type }) },
                    success: function (data) {
                        if (data.status == 'ok') {
                            $this.addClass("cur").siblings(".tpbtn").removeClass("cur");
                            $this.find("i").html(data.times);
                            var m = parseInt($this.siblings().find("i").text());
                            if (m > 0 && data.isFrist == false) {
                                $this.siblings().find("i").html(m - 1);
                            }
                        }
                        $this.attr("data-click", false);
                    }
                });
            }
        })
    }
    $.fn.submitMyScore = function (myscore) {
        return this.each(function () {
            var $this = $(this);
            var genneralId = $(".ymw_stars").attr("data-generalid");
            var sorce = myscore * 2;
            $.ajax({
                type: "GET",
                dataType: "jsonp",
                url: "http://cm1.gamersky.com/apirating/addrating",
                data: { 'Rating': JSON2.stringify({ "GenneralId": genneralId, 'Sorce': sorce, 'Type': "0" }) },
                success: function (data) { }
            })
        })
    }
    $.fn.getRating = function () {
        var $this = $(this);
        var genneralId = $this.attr("data-generalid");
        $.ajax({
            type: "GET",
            dataType: "jsonp",
            url: "http://cm1.gamersky.com/apirating/getuserrating",
            data: { 'Rating': JSON2.stringify({ "GenneralId": genneralId, 'Type': "0" }) },
            success: function (data) {
                if (data.status == "ok" && data.sorce > 0) {
                    var n = parseInt(data.sorce / 2);
                    var txt = $(".ymw_stars a[data-sorce=" + data.sorce + "]").attr("data-txt");
                    $(".ymw_zp_area_star").find("span").html(txt);
                    for (var i = 0; i < n; i++) {
                        $this.find("a").eq(i).addClass("cur");
                    }
                }
            }
        });
    }
    $.fn.getuserRating = function () {
        var $this = $(this);
        var genneralId = $this.attr("data-generalid");
        $.ajax({
            type: "GET", dataType: "jsonp", url: "http://cm1.gamersky.com/apirating/getplayersscore",
            data: { jsondata: JSON2.stringify({ genneralId: genneralId, num: "10" }) },
            success: function (responseJson) {
                if (responseJson.status == 'ok') {
                    $this.find("i").html(responseJson.sorce);
                }

            }
        });
    }
    $.fn.judgewanFun = function () {
        var ids = "";
        $(".tpbtn[data-type='7']").each(function () {
            if (ids != "") {
                ids = ids + ","
            }
            ids = ids + $(this).attr("gameid");
        });
        $.ajax({
            type: "GET",
            dataType: "jsonp",
            url: "http://cm1.gamersky.com/apirating/Judge",
            data: { 'Idlist': ids },
            success: function (data) {
                if (data.status == "ok") {
                    $.each(data.result, function (index, value) {
                        if (value.wantPlay == 'True') {
                            $(".tpbtn[gameid='" + value.gameId + "'][data-type='7']").addClass("cur");
                        }
                        if (value.played == 'True') {
                            $(".tpbtn[gameid='" + value.gameId + "'][data-type='8']").addClass("cur");
                        }
                    });
                }
            }
        });
    }
    $('.ymw-btns-pc').attr('target', '_blank')
    $('.ymw-btns-pc').on('click', function () {
        var cookieval = 'wapopenpc', cookievalTime = 'wapopenpctimeout';
        if ($.fn.cookie(cookieval) == undefined || $.fn.cookie(cookieval) == null) {
            $.fn.cookie(cookieval, 'yes', { path: '/', domain: '.gamersky.com' })
        }
        if ($.fn.cookie(cookievalTime) == undefined || $.fn.cookie(cookievalTime) == null) {
            $.fn.cookie(cookievalTime, 'yes', { path: '/', domain: '.gamersky.com', expires: 0.5 })
        }
    })

    $('.tpbtn').on('touchend', function () {
        var $this = $(this);
        if ($this.hasClass("stop")) { alert("该游戏未上市！"); return false; }
        $.ajax({
            type: "GET", dataType: "jsonp", url: "http://i.gamersky.com/api/logincheck",
            success: function (responseJson) {
                if (responseJson.status == "ok") {
                    $this.addwanFun();
                }
                else {
                    $(".ymw-loginpop-btns").insertYmwLoginPop();
                    $(".ymw-loginpop-btns").QZloginForm();
                }
            }
        })
    })

    $.fn.QZloginForm = function () {
        var $this = $(this);
        $this.on("click", "#qqLogin", function (event) {
            event.preventDefault();
            var returnUrl = window.location.href;
            window.location.href = "http://i.gamersky.com/oauth/authorizelogin?authorizetype=qq&returnUrl=" + encodeURI(returnUrl);
        }).on("click", "#sinaLogin", function (event) {
            event.preventDefault();
            var returnUrl = window.location.href;
            window.location.href = "http://i.gamersky.com/oauth/authorizelogin?authorizetype=sina&returnUrl=" + encodeURI(returnUrl);
        })
    }
    $.fn.insertYmwLoginPop = function () {
        var returnUrl = encodeURI(window.location.href);
        var ymwLoginDom = '';
        ymwLoginDom += '<div class="ymw-loginpopMsk"></div><div class="ymw-loginpop"><h5>登录后参加互动</h5><p><span>你可以通过一下方式登录</span></p><div class="ymw-loginpop-btns">';
        //游民登录
        ymwLoginDom += '<a target="_blank" href="http://i.gamersky.com/user/login.html?from=' + returnUrl + '" class="ymw-loginpop-gs"></a>';
        //QQ登录
        ymwLoginDom += '<a target="_blank" href="javascript:;" id="qqLogin" class="ymw-loginpop-qq"></a>';
        //微博登录
        ymwLoginDom += '<a target="_blank" href="javascript:;"  id="sinaLogin" class="ymw-loginpop-wb"></a>';
        ymwLoginDom += '</div></div>';
        $('body').append(ymwLoginDom);
        //点击弹窗外部关闭弹窗
        $('.ymw-loginpopMsk').on('click', function () {
            removeYmwLoginPop();
        })
    }

})(jQuery)
$(function () {
    $(".tpbtn").wanFun();
    $(".ymw_zp_pf_wd").judgewanFun();
    $(".ymw_stars").getRating();
    $(".ymw_zp_pf_res").getuserRating();
    checkMarketTime(".pingtai");
})
function addPcNum() {
    function pc(str1, str2) {
        if ($(str1).length > 0) {
            var $str1 = $(str1), n = $str1.find(str2).text();
            if (n.indexOf(".") != -1) { n = Number(n.split(".")[1]) > 0 && Number(n.split(".")[1]) < 5 ? n.split(".")[0] + ".5" : Number(n).toFixed(); }
            n = n.replace(/.{0}/, "n").replace(".", "-");
            $str1.find(str2).attr("class", "pnum " + n);
        }
    }
    pc(".pingce2", ".pnum"); //游民点评
    pc(".dianping", ".pnum");    //游民点评
}
function contentJs() {
    for (var m = 0; m < document.getElementsByTagName("span").length; m++) {
        if (document.getElementsByTagName("span")[m].style.color == "rgb(255, 204, 0)") {
            document.getElementsByTagName("span")[m].style.color = "#d26217";
        }
        if (document.getElementsByTagName("span")[m].color == "#ffcc00" || document.getElementsByTagName("span")[m].color == "rgb(255, 204, 0)") {
            document.getElementsByTagName("span")[m].color = "#d26217";
        }
        //翠绿色替换
        if (document.getElementsByTagName("span")[m].color == "#00ee00") {
            document.getElementsByTagName("span")[m].color = "#228B22";
        }
    }
    for (var t = 0; t < document.getElementsByTagName("strong").length; t++) {
        if (document.getElementsByTagName("strong")[t].style.color == "rgb(255, 204, 0)") {
            document.getElementsByTagName("strong")[t].style.color = "#d26217";
        }
        if (document.getElementsByTagName("strong")[t].color == "#ffcc00" || document.getElementsByTagName("strong")[t].color == "rgb(255, 204, 0)") {
            document.getElementsByTagName("strong")[t].color = "#d26217";
        }
        //翠绿色替换
        if (document.getElementsByTagName("strong")[t].color == "#00ee00") {
            document.getElementsByTagName("strong")[t].color = "#228B22";
        }
    }

    for (var n = 0; n < document.getElementsByTagName("font").length; n++) {
        if (document.getElementsByTagName("font")[n].style.color == "rgb(255, 204, 0)") {
            document.getElementsByTagName("font")[n].style.color = "#d26217";
        }
        if (document.getElementsByTagName("font")[n].color == "#ffcc00" || document.getElementsByTagName("font")[n].color == "rgb(255, 204, 0)") {
            document.getElementsByTagName("font")[n].color = "#d26217";
        }
        //翠绿色替换
        if (document.getElementsByTagName("font")[n].color == "#00ee00") {
            document.getElementsByTagName("font")[n].color = "#228B22";
        }
        //黄色替换
        if (document.getElementsByTagName("font")[n].color == "#FFFF00") {
            document.getElementsByTagName("font")[n].color = "#ff6000";
        }
    }
    // var iframeLength = document.getElementsByTagName("iframe").length;
    // var embedLenfth = document.getElementsByTagName("embed").length;
    // $("#leshitvauto").height(document.body.clientWidth * (9 / 16)).width(document.body.clientWidth - 20);
    //
    // if (iframeLength > 0) {
    //     for (var i = 0; i < iframeLength; i++) {
    //         var iframeElements = document.getElementsByTagName("iframe")[i];
    //         if (iframeElements.style["display"] != "none") {
    //             iframeElements.removeAttribute("style");
    //         }
    //         iframeElements.height = document.body.clientWidth * (9 / 16);
    //         iframeElements.width = document.body.clientWidth - 20;
    //     }
    //
    // }
    // if (embedLenfth > 0) {
    //     for (var n = 0; n < embedLenfth; n++) {
    //         if (document.getElementsByTagName("embed")[n].style["display"] != "none") {
    //             document.getElementsByTagName("embed")[n].removeAttribute("style");
    //         }
    //         document.getElementsByTagName("embed")[n].height = document.body.clientWidth * (9 / 16);
    //         document.getElementsByTagName("embed")[n].width = document.body.clientWidth - 20;
    //     }
    // }
    var blockreference = $(".blockreference").html();
    if ($(".blockreference").length > 0) {
        if ($(".referencecontent").length > 0) {
            $(".referencecontent").html(blockreference);
            $(".blockreference").remove();
        } else {
            $(".blockreference").css("display", "block");
        }
    }
};

function judgeTime(sellTime) {
    var reg = new RegExp("[\\u4E00-\\u9FFF]+");
    if (reg.test(sellTime)) {
        return false;
    }
    else {
        var myDate = new Date();
        var year = myDate.getFullYear();
        var month = myDate.getMonth() + 1;
        var date = myDate.getDate();
        var h = myDate.getHours();
        var m = myDate.getMinutes();
        var s = myDate.getSeconds();
        var now = year + '-' + padleft0(month) + "-" + padleft0(date);
        if (!checkEndTime(sellTime, now)) {
            return false;
        }
    }
    return true;
};

function checkMarketTime(div) {
    $(div).find("a").each(function () {
        var $this = $(this);
        var reg = /\(.*?\)/g;
        var time = $this.attr("data-time").replace(reg, "");
        time = time.replace("（", "(").replace("）", ")");
        if (judgeTime(time)) {
            $(".ymw_zp_pf_wd").attr("date-selltime", "已上市");
            return false
        }
        else {
            $(".ymw_zp_pf_wd").attr("date-selltime", "未上市");

        }
    })
	 setTimeout(function () { judgeListedState(".ymw_zp_pf_wd") }, 200);
}
function judgeListedState(div) {
    $(div).each(function () {
        var $this = $(this);
        var sellTime = $this.attr("date-selltime");
        if (sellTime == '未上市') {
            $(div).find("a").eq(1).attr("Class", "stop");
        }
    })
};
//补齐两位数  
function padleft0(obj) {
    return obj.toString().replace(/^[0-9]{1}$/, "0" + obj);
}
//比较日期大小
function checkEndTime(startTime, endTime) {
    if (typeof (startTime) == "undefined" || typeof (endTime) == "undefined") {
        return;
    }
    var start = new Date(startTime.replace("-", "/").replace("-", "/"));
    var end = new Date(endTime.replace("-", "/").replace("-", "/"));
    if (end < start) {
        return false;
    }
    return true;
};


function removeYmwLoginPop() {
    $('.ymw-loginpopMsk,.ymw-loginpop').remove();
}

